#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <net/ethernet.h>
#include <netinet/ether.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <string>
#include <net/ethernet.h>
#include <iostream>
//#include <ether.h>
#include "definitions.hpp"

using namespace std;

void* rdwrif1_thread_func(void* x){

	int sock_eth;

	 if ((sock_eth = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL))) < 0) {
        perror("socket");
        exit(1);
    }


	/*if ((sock_ip = socket(AF_INET, SOCK_RAW, IPPROTO_IP)) < 0) {
        perror("socket");
        exit(1);
    }

    if ((ret = setsockopt(sock_ip, IPPROTO_IP, IP_HDRINCL, (char *)&one,
                     sizeof(one))) < 0) {
        perror("setsockopt");
        exit(1);
    }*/

	 map<string,string>::iterator it;
	 string macadd;
	 string inter;


	it = ipadd_map.find("10.10.0");
	if(it!=ipadd_map.end()){
	string parse = it->second;
	int k = parse.find_first_of(",");
	macadd = parse.substr(0,k);
	cout<<"MACADD "<<macadd<<endl;
	cout<<"PARSE "<<parse<<endl;
	inter = parse.substr(k+1, (parse.length())-(k+1));
	}else{

		cerr<<"IP value in the rdwrif1 does not exist"<<endl;

	}

	 struct sockaddr from;
     int fromlen;

     memset(&from, '\0', sizeof(from));
     from.sa_family = AF_INET;
     strcpy(from.sa_data, inter.c_str()); /* or whatever device */
     fromlen = sizeof(from);




 while(1){
	 if(packet_q_i2.size() <= 0){
	 usleep(100);
		 continue;
	 }
  unsigned char* buf = packet_q_i2.front();
  packet_q_i2.pop_front();


  // Read the raw message // Begin

   struct sniff_ethernet *eth_hdr;
   struct ip *ip_hdr_in, *ip_hdr_out;

  	eth_hdr     = (struct sniff_ethernet *)buf;
    ip_hdr_in   = (struct ip *)(buf + sizeof(struct ether_header));
	ip_hdr_out   = (struct ip *)buf;

	uint8_t ttl;

	memcpy(&ttl,&ip_hdr_in->ip_ttl,1);

	if(ttl == 1){
		//Send ICMP back
		continue;
	}
    ttl = ttl-1;

	memcpy(&ip_hdr_in->ip_ttl,&ttl,1);

	ip_hdr_out->ip_sum = in_cksum((unsigned short *)buf,ip_hdr_in->ip_hl);

	memcpy(eth_hdr->ether_shost,eth_hdr->ether_dhost,ETHER_ADDR_LEN);
    memcpy(eth_hdr->ether_dhost,macadd.c_str(),ETHER_ADDR_LEN);


  // Read the raw message // End


// Write into a raw socket // 
   int r;

     r = sendto(sock_eth, buf, sizeof(buf), 0, &from, fromlen);
	 if(r <0) {
		 perror("sendto-if1");
	 }


 //free(buf);

}// while(1)
}//rdwr function


